package com.yunxi.core.util;
/*
 * RandomGUID
 * @version 1.2 01/29/02
 * @author Marc A. Mnich
 *
 * From www.JavaExchange.com, Open Software licensing
 *
 * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object
 *             caused duplicate GUIDs to be produced.  Random object
 *             is now only created once per JVM.
 * 01/19/02 -- Modified random seeding and added new constructor
 *             to allow secure random feature.
 * 01/14/02 -- Added random function seeding with JVM run time
 *
 */

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class GUIDGenerator extends Object {

	private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    private final static char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z'};
	
	public String valueBeforeMD5 = "";

    public String valueAfterMD5 = "";

    private static Random myRand;

    private static SecureRandom mySecureRand;

    static {
        mySecureRand = new SecureRandom();
        long secureInitializer = mySecureRand.nextLong();
        myRand = new Random(secureInitializer);
    }

    public GUIDGenerator() {
        getRandomGUID(false);
    }

    public GUIDGenerator(boolean secure) {
        getRandomGUID(secure);
    }

    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        try {
            InetAddress id = InetAddress.getLocalHost();
            long time = System.currentTimeMillis();
            long rand = 0;

            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }

            sbValueBeforeMD5.append(id.toString());
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));

            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());

            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; j++) {
                int b = array[j] & 0xFF;
                if (b < 0x10)
                    sb.append('0');
                sb.append(Integer.toHexString(b));
            }

            valueAfterMD5 = sb.toString();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public String toString() {
        String raw = valueAfterMD5.toUpperCase();
        StringBuffer sb = new StringBuffer();
        sb.append(raw.substring(0, 8));
        //sb.append("-");
        sb.append(raw.substring(8, 12));
        //sb.append("-");
        sb.append(raw.substring(12, 16));
        //sb.append("-");
        sb.append(raw.substring(16, 20));
        //sb.append("-");
        sb.append(raw.substring(20));

        return sb.toString();
    }

    public static String getGUID() {
        GUIDGenerator myGUID = new GUIDGenerator();
        return myGUID.toString();
    }
    
    /**
     * 获得主键
     *
     * @return String
     */
    public static String getPrimaryKey() {
        UUID uuid = UUID.randomUUID();
        return dateformat.format(new Date()) + uuid.toString().replaceAll("-", "").substring(0, 16);
    }
    
    public static String getSeqKey(){
        java.util.Date dt=new java.util.Date();
        long lg=dt.getTime();
        Long ld=new Long(lg);
        String RecordID=ld.toString();
        return RecordID;
    }

    public static void main(String args[]) {
        GUIDGenerator myGUID = new GUIDGenerator();
        Date start = new Date();
        System.out.println("RandomGUID=" + GUIDGenerator.getGUID()+"|"+ GUIDGenerator.getGUID().length());
        System.out.println("RandomGUID=" + myGUID.toString());
        System.out.println("UUID=" + UUID.randomUUID().toString()+"|"+ UUID.randomUUID().toString().length());
        Date end = new Date();
        System.out.println("Time:" + (end.getTime() - start.getTime()) + "ms.");
    }

}
